package com.github.postsanf.yinian.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseFragment;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.AlbumFuliDialogActivity;
import com.github.postsanf.yinian.activity.AlbumManageActivity;
import com.github.postsanf.yinian.activity.CreateZoneActivity;
import com.github.postsanf.yinian.activity.InviteChooseActivity;
import com.github.postsanf.yinian.activity.LineTimeStatusShareActivity;
import com.github.postsanf.yinian.activity.MemberActivity;
import com.github.postsanf.yinian.activity.PicWallActivity;
import com.github.postsanf.yinian.activity.SharePhotoActivity;
import com.github.postsanf.yinian.activity.StealCourseVideoActivity;
import com.github.postsanf.yinian.activity.StealEachPerssionActivity;
import com.github.postsanf.yinian.activity.StealPhotosWarningDialogActivity;
import com.github.postsanf.yinian.activity.TimeImpressActivity;
import com.github.postsanf.yinian.activity.pop.PopSetAvatar;
import com.github.postsanf.yinian.activity.pop.PopShareTimeLine;
import com.github.postsanf.yinian.adapter.MembersHorizontalAdapter;
import com.github.postsanf.yinian.adapter.TimeLineStatusAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNLike;
import com.github.postsanf.yinian.bean.YNMember;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNAlbumMemberResponse;
import com.github.postsanf.yinian.service.AlbumContentService;
import com.github.postsanf.yinian.service.AlbumService;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.github.postsanf.yinian.widget.FeedRootRecyclerView;
import com.github.postsanf.yinian.widget.MySlidingMenu;
import com.github.postsanf.yinian.ynlist.LoadingFooter;
import com.github.postsanf.yinian.ynlist.RecyclerViewStateUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import sweetcamera.CameraActivity;

public class PeopleTimeLineFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    private View view;
    private FeedRootRecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshlayout;
    private TimeLineStatusAdapter mTimeLineStatusAdapter;
    private List<YNStatus> groupStatusItems = new ArrayList<>();
    private boolean isBottom = false;
    private boolean refresh = false;
    private RelativeLayout members_horizontal;
    private TextView peoplespace_title;
    private MySlidingMenu menu;
    private RecyclerView members_recycler_horizontal;
    private MembersHorizontalAdapter mAdapter;
    private List<YNMember> mMemberDatas = new ArrayList<>();
    private YNAlbum curAlbum;
    private RelativeLayout menu_invite_guide_rl;
    private ImageView iv_red_point;
    private SimpleDraweeView iv_album_top;
    private TextView mem_album_name;
    private TextView sliding_member;
    private PopSetAvatar mpopSetAvatar;
    private PopShareTimeLine mpopShareTimeLine;
    private RelativeLayout status;
    private RelativeLayout status_empty;
    private RelativeLayout ll_album_manage_content;
    public static int MembersNum = 1;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        registerBroadcastReceiver();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        noticeFristInit();
        initView();
        judgeImagesPerssion();
        return view;
    }

    private void initView() {
        view = View.inflate(getActivity(), R.layout.yn_people_timeline_status, null);
        status = (RelativeLayout) view.findViewById(R.id.status);
        status_empty = (RelativeLayout) view.findViewById(R.id.status_empty);
        view.findViewById(R.id.status_empty_btn).setOnClickListener(this);
        ll_album_manage_content = (RelativeLayout) view.findViewById(R.id.ll_album_manage_content);
        peoplespace_title = (TextView) view.findViewById(R.id.peoplespace_title);
        mpopSetAvatar = new PopSetAvatar(getActivity(), itemsOnClick, itemsOnTouch);
        mpopShareTimeLine = new PopShareTimeLine(getActivity(), itemsOnClick2, itemsOnTouch2);
        view.findViewById(R.id.iv_pailide_sao).setOnClickListener(this);
        view.findViewById(R.id.iv_slidingmenu).setOnClickListener(this);
        view.findViewById(R.id.iv_fristmember_avatar).setOnClickListener(this);
        members_recycler_horizontal = (RecyclerView) view.findViewById(R.id.members_recycler_horizontal);
        members_recycler_horizontal.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        members_recycler_horizontal.setHasFixedSize(true);
        mAdapter = new MembersHorizontalAdapter(getActivity(), mMemberDatas, application.getCurGid());
        members_recycler_horizontal.setAdapter(mAdapter);
        menu = new MySlidingMenu(getActivity());
        menu.setMode(MySlidingMenu.RIGHT);
        menu.setTouchModeAbove(MySlidingMenu.TOUCHMODE_NONE);
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        menu.setBehindWidth(UIHelper.dip2px(getActivity(), 266));
        menu.setFadeEnabled(true);
        menu.setOffsetFadeDegree(0.6f);
        menu.setFadeDegree(0.35f);
        menu.attachToActivity(getActivity(), MySlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.slidingmenu_right);
        members_horizontal = (RelativeLayout) view.findViewById(R.id.members_horizontal);
        menu.addIgnoredView(members_horizontal);
        iv_album_top = (SimpleDraweeView) menu.getMenu().findViewById(R.id.iv_album_top);
        mem_album_name = (TextView) menu.getMenu().findViewById(R.id.mem_album_name);
        iv_red_point = (ImageView) menu.getMenu().findViewById(R.id.iv_red_point);
        sliding_member = (TextView) menu.getMenu().findViewById(R.id.sliding_member);
        menu_invite_guide_rl = (RelativeLayout) menu.getMenu().findViewById(R.id.menu_invite_guide_rl);
        iv_album_top.setOnClickListener(this);
        menu_invite_guide_rl.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                menu_invite_guide_rl.setVisibility(View.GONE);
                SpUtils.put(getActivity(), "MenuInvite", true);
            }
        });
        menu.getMenu().findViewById(R.id.smenu0).setOnClickListener(this);
        menu.getMenu().findViewById(R.id.smenu1).setOnClickListener(this);
        menu.getMenu().findViewById(R.id.smenu2).setOnClickListener(this);
        menu.getMenu().findViewById(R.id.smenu3).setOnClickListener(this);
        menu.getMenu().findViewById(R.id.smenu4).setOnClickListener(this);
        menu.getMenu().findViewById(R.id.smenu5).setOnClickListener(this);
        menu.getMenu().findViewById(R.id.smenu_fuli).setOnClickListener(this);
        menu.setOnCloseListener(new MySlidingMenu.OnCloseListener() {
            @Override
            public void onClose() {
                getActivity().sendBroadcast(new Intent("mViewPagerOne"));
                menu_invite_guide_rl.setVisibility(View.GONE);
                SpUtils.put(getActivity(), "MenuInvite", true);
            }
        });
        if (!SpUtils.getBoolean(getActivity(), "MenuInvite")) {
            menu_invite_guide_rl.setVisibility(View.VISIBLE);
            menu.toggle();
        }
        mRecyclerView = (FeedRootRecyclerView) view.findViewById(R.id.album_status_recyclerview);
        mRefreshlayout = (SwipeRefreshLayout) view.findViewById(R.id.album_status_swipe_refresh);
        mRefreshlayout.setColorSchemeColors(getResources().getColor(R.color.yncolor));
        mRefreshlayout.setOnRefreshListener(this);
        mRefreshlayout.post(new Runnable() {
            @Override
            public void run() {
                mRefreshlayout.setRefreshing(true);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                int visibleItemCount = layoutManager.getChildCount();
                int totalItemCount = layoutManager.getItemCount();
                if (visibleItemCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE && (((LinearLayoutManager) layoutManager).findLastVisibleItemPosition()) >= totalItemCount - 1) {
                    if (isBottom) {
                        return;
                    }
                    LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
                    if (state == LoadingFooter.State.Loading) {
                        return;
                    }
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, 10, LoadingFooter.State.Loading, null);
                    mRecyclerView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadStatus(false, ACTIONs.actionAlbumStatus);
                        }
                    }, 600);
                }
            }
        });
        boolean isKuoRongShow = SpUtils.getBoolean(getActivity(), "isKuoRongShow");
        if (!isKuoRongShow)
            startActivity(new Intent(getActivity(), AlbumFuliDialogActivity.class));
    }


    public static boolean isPerssionGood = false;

    private void judgeImagesPerssion() {
        Log.i("xjs", "judgeImagesPerssion===>");
        String urlsto = getString(R.string.SLIVER_URL) + "GetUserAllPhotoHash";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.optString("msg").equals("success")) {
                                if (jsonObject.optJSONArray("data").length() < 3) {
                                    isPerssionGood = false;
                                    cancelAllPerssion();
                                } else {
                                    isPerssionGood = true;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void cancelAllPerssion() {
        Log.i("xjs", "cancelAllPerssion===>");
        String urlsto = getString(R.string.SLIVER_URL) + "AuthorizeOrCancelForWatchPhoto";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_TYPE, "cancelAll");
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            Log.i("xjs", "cancelAllPerssion==>" + s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void updatebg() {
        String urls = (curAlbum == null || curAlbum.getGpic() == null) ? "" : curAlbum.getGpic();
        ImageOptHelper.showFrescoBlur(Uri.parse(urls), iv_album_top, getActivity());
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                noticeServiceInit(true);
            }
        }, 500);
    }

    // 更新动态数据
    private void updateView(boolean isTop) {
        mRefreshlayout.setRefreshing(false);
        if (isTop) {
            if (YNSingleton.getInstance().getStatusList() == null)
                return;
            mTimeLineStatusAdapter.addItemsFromTop(YNSingleton.getInstance().getStatusList());
            mRecyclerView.scrollToPosition(0);
        } else {
            mTimeLineStatusAdapter.addItemsFromBottom(YNSingleton.getInstance().getStatusList());
            if (YNSingleton.getInstance().getStatusList().size() == 0) {
                isBottom = true;
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, 10, LoadingFooter.State.TheEnd, null);
            } else {
                RecyclerViewStateUtils.setFooterViewState(mRecyclerView, LoadingFooter.State.Normal);
            }
        }
        if (refresh) {
            mTimeLineStatusAdapter.notifyDataSetChanged();
            refresh = false;
        }
    }

    // 普通相册加载
    private void loadStatus(boolean isTop, String action) {
        if (getActivity() == null) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), AlbumContentService.class);
        mIntent.setAction(action);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra(ACTIONs.aLoadId, mTimeLineStatusAdapter.getIdByDirection(isTop));
        getActivity().startService(mIntent);
    }


    public static boolean buttonsCanClick = true;

    YNStatus ynStatus;
    BroadcastReceiver mStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "doClickShare":
                    ynStatus = (YNStatus) intent.getSerializableExtra("ynStatus");
                    if (ynStatus.getPicList() != null && ynStatus.getPicList().size() > 0) {
                        if (ynStatus.geteMain() == 4) {
                            mpopShareTimeLine.getContentView().findViewById(R.id.btn_setuser_take_photo).setVisibility(View.GONE);
                        } else {
                            mpopShareTimeLine.getContentView().findViewById(R.id.btn_setuser_take_photo).setVisibility(View.VISIBLE);
                        }
                        mpopShareTimeLine.showAtLocation(ll_album_manage_content, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    } else {
                        String url = "http://wx.zhuiyinanian.com/app/sharedetail.html?code=";
                        String sec = null;
                        try {
                            sec = YNInviteSecret.encryptDES("eid=" + ynStatus.getEid(), getActivity().getResources().getString(R.string.UNKNOW_ID));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        url = url + sec;
                        Intent sintent = new Intent(getActivity(), LineTimeStatusShareActivity.class);
                        sintent.putExtra("UrlShare", url);
                        sintent.putExtra("title", ynStatus.getPublishUser().getUnickname() + "有一段美好时光@你");
                        sintent.putExtra("desc", "喊你进ta的时光隧道看看啦");
                        sintent.putExtra("avatarPaths", MineFragement.avatarPic);
                        getActivity().startActivity(sintent);
                    }
                    break;
                case "doPaiLideShare":
                    ynStatus = (YNStatus) intent.getSerializableExtra("ynStatus");
                    String url = "http://wx.zhuiyinanian.com/app/shareHiddenEvent.html?code=";
                    String sec = null;
                    try {
                        sec = YNInviteSecret.encryptDES("eid=" + ynStatus.getEid(), getActivity().getResources().getString(R.string.UNKNOW_ID));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    url = url + sec
                            + "&fromUserID=" + application.getCurID()
                            + "&fromSpaceID=" + application.getCurGid()
                            + "&fromEventID=" + sec
                            + "&port=App拍立得分享";
//                    Intent sintent = new Intent(getActivity(), LineTimeStatusShareActivity.class);
//                    sintent.putExtra("UrlShare", url);
//                    sintent.putExtra("title", "根据我提供的线索拿起手机拍个照，猜猜我藏了什么？");
//                    sintent.putExtra("desc", "快拿起手机拍个照！");
//                    sintent.putExtra("avatarPaths", MineFragement.avatarPic);
//                    getActivity().startActivity(sintent);
                    UMMin umMin = new UMMin(url);
                    umMin.setThumb(new UMImage(getActivity(), R.drawable.invite_wxminshare));
                    umMin.setTitle("根据我提供的线索拿起手机拍个照，猜猜我藏了什么？");
                    umMin.setDescription("快拿起手机拍个照！");
                    umMin.setPath("pages/sharehtml/pailide/pailide?groupid=" + application.getCurGid() + "&eid=" + ynStatus.getEid() + "&fromUserID=" + application.getCurID()
                            + "&fromSpaceID=" + application.getCurGid()
                            + "&fromEventID=" + ynStatus.getEid() + "&port=App拍立得分享");
                    umMin.setUserName("gh_11ddcc4aabbb");
                    new ShareAction(getActivity())
                            .withMedia(umMin)
                            .setPlatform(SHARE_MEDIA.WEIXIN)
                            .setCallback(umShareListener).share();
                    break;
                case "doClickZan":
                    ynStatus = (YNStatus) intent.getSerializableExtra("ynStatus");
                    String zantype = intent.getStringExtra("type");
                    doClickZan(ynStatus.getEid(), zantype);
                    break;
                case "SlidingMenuCanOpen":
//                    if (intent.getBooleanExtra("canopen", false)) {
//                        menu.setTouchModeAbove(MySlidingMenu.TOUCHMODE_FULLSCREEN);
//                    } else {
//                        menu.setTouchModeAbove(MySlidingMenu.TOUCHMODE_NONE);
//                    }
                    break;
                case "SlidingMenuOpen":
                    if (buttonsCanClick)
                        menu.toggle();
                    break;
                case ACTIONs.actionUpdateFristAlbum:
                    buttonsCanClick = true;
                    status_empty.setVisibility(View.GONE);
                    status.setVisibility(View.VISIBLE);
                    boolean update = false;
                    if (intent != null) {
                        update = intent.getBooleanExtra("update", false);
                    }
                    curAlbum = YNSingleton.getInstance().getCurAlbum();
                    application.setCurGid(curAlbum.getGroupid());
                    application.setCurgimid(curAlbum.getGimid());
                    noticeMembersServiceInit();
                    if (curAlbum != null && curAlbum.getGnum() != null) {
                        sliding_member.setText("成员（" + curAlbum.getGnum() + "）");
                        peoplespace_title.setText(curAlbum.getGname());
                        if (curAlbum.getGnum().equals("1")) {
                            iv_red_point.setVisibility(View.VISIBLE);
                        } else {
                            iv_red_point.setVisibility(View.GONE);
                        }
                    }
                    updatebg();
                    mem_album_name.setText(curAlbum.getGname());
                    groupStatusItems.clear();
                    isBottom = false;
                    mTimeLineStatusAdapter = new TimeLineStatusAdapter(getActivity(), groupStatusItems, application.getCurID(), true);
                    mRecyclerView.setAdapter(mTimeLineStatusAdapter);
                    noticeServiceInit(update);
                    judgeImagesPerssion();
                    boolean openpublish = false;
                    if (intent != null) {
                        openpublish = intent.getBooleanExtra("openpublish", false);
                    }
                    if (openpublish) {
                        context.sendBroadcast(new Intent("OpenButtons"));
                    }
                    break;
                case ACTIONs.actionUpdateEmptyAlbum:
                    buttonsCanClick = false;
                    status.setVisibility(View.GONE);
                    status_empty.setVisibility(View.VISIBLE);
                    break;
                case ACTIONs.actionStatusUpdate:
                    boolean bbupdate = intent.getBooleanExtra("update", false);
                    updateView(bbupdate);
                    break;
                case ACTIONs.actionStatusUpdateRefresh:
                    updateView(true);
                    break;
                case ACTIONs.actionOfficialStatusUpdate:
                    boolean istop = intent.getBooleanExtra("isTop", false);
                    updateView(istop);
                    break;
                case ACTIONs.actionComment:
                    if (mTimeLineStatusAdapter != null)
                        mTimeLineStatusAdapter.SyncComment();
                    break;
                case ACTIONs.actionLike:
                    mTimeLineStatusAdapter.SyncLike();
                    break;
                case ACTIONs.actionStatus:
                    boolean isAdd = intent.getExtras().getBoolean(ACTIONs.IsAdd);
                    int statusID = intent.getExtras().getInt(ACTIONs.StatusId);
                    doSyncStatus(isAdd, statusID);
                    break;
                case ACTIONs.actionSinglePhoto:
//                    String PhotoUrl = intent.getStringExtra(ACTIONs.PhotoUrl);
//                    for (int i = 0; i < groupStatusItems.size(); i++) {
//                        if (PhotoUrl != null && PhotoUrl.equals(groupStatusItems.get(i).getUrl())) {
//                            groupStatusItems.remove(i);
//                            mTimeLineStatusAdapter.notifyItemRemoved(i);
//                            break;
//                        }
//                    }
                    mTimeLineStatusAdapter.SyncDelSingle();
                    break;
                case ACTIONs.actionStatusDleteUpdate:
                    loadStatus(true, ACTIONs.actionAlbumStatusRefresh);
                    break;
                case ACTIONs.actionLookStatus:
                    if (intent != null) {
                        int eid = intent.getIntExtra("eid", 0);
                        lookStatus(eid);
                    }
                    break;
                case ACTIONs.modifyStatus:
                    groupStatusItems.clear();
                    refresh = true;
                    noticeServiceInit(false);
                    break;
                case "updatebgImg":
                    String bgUrl = intent.getStringExtra("img");
                    ImageOptHelper.showFrescoBlur(Uri.parse("file:///" + bgUrl), iv_album_top, getActivity());
                    break;
                case ACTIONs.actionGroupQuit:
                    noticeFristInit();
                    break;
                case ACTIONs.actionAlertGName:
                    curAlbum.setGname(YNSingleton.getInstance().getCurAlbum().getGname());
                    peoplespace_title.setText(YNSingleton.getInstance().getCurAlbum().getGname());
                    mem_album_name.setText(YNSingleton.getInstance().getCurAlbum().getGname());
                    break;
                case ACTIONs.actionAlertGPic:
                    curAlbum.setGpic(YNSingleton.getInstance().getCurAlbum().getGpic());
                    updatebg();
                    break;
                case "StealPhotosWarning":
                    judgeCourseIsLook();
                    break;
            }
        }
    };


    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(getActivity(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getActivity(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getActivity(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };


    // 同步动态
    private void doSyncStatus(boolean isAdd, int statusID) {
        if (isAdd) {
            if (statusID == YNSingleton.getInstance().getCurStatus().getEid()) {
                mTimeLineStatusAdapter.addItemsFromTopOne(YNSingleton.getInstance().getCurStatus());
                mRecyclerView.scrollToPosition(0);
            }
        } else {
            mTimeLineStatusAdapter.removeOne(statusID);
        }
    }

    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionStatusUpdate);
        myIntentFilter.addAction(ACTIONs.actionStatusDleteUpdate);
        myIntentFilter.addAction(ACTIONs.actionStatusUpdateRefresh);
        myIntentFilter.addAction(ACTIONs.actionOfficialStatusUpdate);
        myIntentFilter.addAction(ACTIONs.actionComment);
        myIntentFilter.addAction(ACTIONs.actionLike);
        myIntentFilter.addAction(ACTIONs.actionStatus);
        myIntentFilter.addAction(ACTIONs.actionSinglePhoto);
        myIntentFilter.addAction(ACTIONs.actionLookStatus);
        myIntentFilter.addAction(ACTIONs.timeLineLead);
        myIntentFilter.addAction(ACTIONs.modifyStatus);
        myIntentFilter.addAction(ACTIONs.actionUpdateFristAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateEmptyAlbum);
        myIntentFilter.addAction(ACTIONs.actionGroupQuit);
        myIntentFilter.addAction(ACTIONs.actionAlertGName);
        myIntentFilter.addAction(ACTIONs.actionAlertGPic);
        myIntentFilter.addAction("updatebgImg");
        myIntentFilter.addAction("SlidingMenuOpen");
        myIntentFilter.addAction("SlidingMenuCanOpen");
        myIntentFilter.addAction("doClickZan");
        myIntentFilter.addAction("doClickShare");
        myIntentFilter.addAction("doPaiLideShare");
        myIntentFilter.addAction("StealPhotosWarning");
        getActivity().registerReceiver(mStatusBroadcastReceiver, myIntentFilter);
    }

    private void noticeFristInit() {
        Log.i("xjs", "noticeFristInit==》");
        Intent mIntent = new Intent(getActivity(), AlbumService.class);
        mIntent.setAction(ACTIONs.actionGetFristAlbum);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID());
        getActivity().startService(mIntent);
    }

    private void noticeServiceInit(boolean update) {
        if (getActivity() == null) {
            return;
        }
        Intent mIntent = new Intent(getActivity(), AlbumContentService.class);
        mIntent.setAction(ACTIONs.actionAlbumStatus);
        mIntent.putExtra(ACTIONs.aLoadId, 0);
        mIntent.putExtra(ACTIONs.aGroupId, application.getCurGid());
        mIntent.putExtra("update", update);
        getActivity().startService(mIntent);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(mStatusBroadcastReceiver);
    }


    private void lookStatus(int eid) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put("eventid", String.valueOf(eid));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynWatchStatus))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>() {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        super.onSuccess(s, response);
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void noticeMembersServiceInit() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowMember))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAlbumMemberResponse resAlbumMember = gson.fromJson(s, YNAlbumMemberResponse.class);
                        if (resAlbumMember != null && ReqUtils.isSuccess(resAlbumMember.getCode())) {
                            mMemberDatas.clear();
                            YNMember ynMember = new YNMember();
                            YNUser ynUser = new YNUser();
                            ynUser.setUpic("空");
                            ynMember.setUser(ynUser);
                            mMemberDatas.add(ynMember);
                            mMemberDatas.addAll(resAlbumMember.getData());
                            mAdapter.notifyDataSetChanged();
                            MembersNum = mMemberDatas.size();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.status_empty_btn:
                intent2Activity(CreateZoneActivity.class);
                break;
            case R.id.iv_pailide_sao:
                startActivity(new Intent(getActivity(), CameraActivity.class).putExtra("IsSaoMiao", true));
                break;
            case R.id.iv_slidingmenu:
                if (buttonsCanClick) {
                    menu.toggle();
                }
                Intent statintentbtnmenu = new Intent(ACTIONs.record);
                statintentbtnmenu.putExtra("key", "侧边栏按钮_4");
                statintentbtnmenu.putExtra("value", 1);
                getActivity().sendBroadcast(statintentbtnmenu);
                break;
            case R.id.smenu0:
                startActivity(new Intent(getActivity(), PicWallActivity.class));
                menu.toggle();
                break;
            case R.id.smenu1:
                startActivity(new Intent(getActivity(), TimeImpressActivity.class));
                menu.toggle();
                Intent statintentbtjinina = new Intent(ACTIONs.record);
                statintentbtjinina.putExtra("key", "纪念日_4");
                statintentbtjinina.putExtra("value", 1);
                getActivity().sendBroadcast(statintentbtjinina);
                break;
            case R.id.iv_fristmember_avatar:
                Intent intent = new Intent(getActivity(), InviteChooseActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, YNSingleton.getInstance().getCurAlbum());
                startActivity(intent);
                Intent statintentava = new Intent(ACTIONs.record);
                statintentava.putExtra("key", "顶部邀请好友_4");
                statintentava.putExtra("value", 1);
                getActivity().sendBroadcast(statintentava);
                break;
            case R.id.smenu2:
                YNAlbum listItems = YNSingleton.getInstance().getCurAlbum();
                Intent intentm2 = new Intent(getActivity(), InviteChooseActivity.class);
                intentm2.putExtra(CommonConstants.YNDATAS, listItems);
                startActivity(intentm2);
                menu.toggle();
                Intent statintentinvite = new Intent(ACTIONs.record);
                statintentinvite.putExtra("key", "侧边栏·邀请好友_4");
                statintentinvite.putExtra("value", 1);
                getActivity().sendBroadcast(statintentinvite);
                break;
            case R.id.smenu3:
                startActivity(new Intent(getActivity(), AlbumManageActivity.class));
                menu.toggle();
                break;
            case R.id.smenu4:
                Intent mintent = new Intent(getActivity(), MemberActivity.class);
                mintent.putExtra(CommonConstants.YNDATAS, curAlbum);
                startActivity(mintent);
                menu.toggle();
                break;
            case R.id.smenu5:
                if (SpUtils.getBoolean(getActivity(), "StealPhotosWarning")) {
                    judgeCourseIsLook();
                } else {
                    startActivity(new Intent(getActivity(), StealPhotosWarningDialogActivity.class));
                }
                menu.toggle();
                break;
            case R.id.smenu_fuli:
                startActivity(new Intent(getActivity(), AlbumFuliDialogActivity.class));
                break;
            case R.id.iv_album_top:
                if (StringUtils.isOfficialGroup(curAlbum.getGtype()) && !(String.valueOf(application.getCurID()).equals(getString(R.string.numberofme)))) {
                    return;
                }
                mpopSetAvatar.showAtLocation(ll_album_manage_content, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                ((TextView) mpopSetAvatar.mMenuView.findViewById(R.id.btn_alert_avatar_title)).setText("修改圈子背景");
                break;
        }
    }

    // 头像监听
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            mpopSetAvatar.dismiss();
            switch (v.getId()) {
                case R.id.btn_setuser_take_photo:
                    getActivity().sendBroadcast(new Intent("ptlftakephoto"));
                    break;
                case R.id.btn_setuser_pick_photo:
                    getActivity().sendBroadcast(new Intent("ptlfpickphoto"));
                    break;
                case R.id.btn_setuser_cancel_photo:
                    break;
            }
        }
    };

    //	头像
    private View.OnTouchListener itemsOnTouch = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int height = mpopSetAvatar.mMenuView.findViewById(R.id.pop_setuser_advatar_layout).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    mpopSetAvatar.dismiss();
                }
            }
            return true;
        }
    };


    private View.OnClickListener itemsOnClick2 = new View.OnClickListener() {
        public void onClick(View v) {
            mpopShareTimeLine.dismiss();
            switch (v.getId()) {
                case R.id.btn_setuser_take_photo:
                    Intent pintent = new Intent(getActivity(), SharePhotoActivity.class);
                    ArrayList<String> urls = new ArrayList<>();
                    for (int i = 0; i < ynStatus.getPicList().size(); i++) {
                        urls.add(ynStatus.getPicList().get(i).getThumbnail());
                    }
                    pintent.putStringArrayListExtra(ACTIONs.aAddData, urls);
                    getActivity().startActivity(pintent);
                    break;
                case R.id.btn_setuser_pick_photo:
                    String url = "http://wx.zhuiyinanian.com/app/sharedetail.html?code=";
                    String sec = null;
                    try {
                        sec = YNInviteSecret.encryptDES("eid=" + ynStatus.getEid(), getActivity().getResources().getString(R.string.UNKNOW_ID));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    url = url + sec;
                    Intent sintent = new Intent(getActivity(), LineTimeStatusShareActivity.class);
                    sintent.putExtra("UrlShare", url);
                    sintent.putExtra("title", ynStatus.getPublishUser().getUnickname() + "和你分享了ta的生活片段！");
                    sintent.putExtra("desc", "有一段美好时光@你，快来看看吧");
                    sintent.putExtra("avatarPaths", MineFragement.avatarPic);
                    getActivity().startActivity(sintent);
                    break;
                case R.id.btn_setuser_cancel_photo:
                    break;
            }
        }
    };

    private View.OnTouchListener itemsOnTouch2 = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int height = mpopShareTimeLine.mMenuView.findViewById(R.id.pop_setuser_advatar_layout).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    mpopShareTimeLine.dismiss();
                }
            }
            return true;
        }
    };

    private void judgeCourseIsLook() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("groupid", String.valueOf(application.getCurGid()));
        Log.i("xjs", "mParam===>" + mParam.toString());
        String urlsto = getString(R.string.SLIVER_URL) + "GetGroupMemberAuthorizeList";
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "judgeCourseIsLook===>" + s.toString());
                        try {
                            JSONObject result = new JSONObject(s);
                            if (result.optInt("code") == 0) {
                                JSONObject jsonObject = result.optJSONArray("data").optJSONObject(0);
                                int isFinishWatchPhotoTutorial = jsonObject.optInt("isFinishWatchPhotoTutorial");
                                if (isFinishWatchPhotoTutorial == 0) {
                                    startActivity(new Intent(getActivity(), StealCourseVideoActivity.class));
                                } else {
                                    startActivity(new Intent(getActivity(), StealEachPerssionActivity.class));
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void doClickZan(final int eid, final String type) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_EID, String.valueOf(eid));
        mParam.put(CommonConstants.YNS_TYPE, type);
        mParam.put(CommonConstants.YNS_SOURCE, "app");
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/yinian/AttachOrRemoveExpression").setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s.toString());
                            if (jsonObject.optString("msg").equals("success") && jsonObject.optInt("code") == 0) {
                                for (int i = 0; i < YNSingleton.getInstance().getStatusList().size(); i++) {
                                    if (YNSingleton.getInstance().getStatusList().get(i).getEid() == eid) {
                                        List<YNLike> likes = YNSingleton.getInstance().getStatusList().get(i).getLike();
                                        if (likes != null && likes.size() > 0) {
                                            List<YNLike> likesnew = new ArrayList<>();
                                            YNLike ynLike = new YNLike();
                                            ynLike.setUpic(MineFragement.avatarPic);
                                            ynLike.setLikeStatus(Integer.parseInt(type));
                                            ynLike.setLikeUserID(application.getCurID());
                                            likesnew.add(ynLike);
                                            for (int j = 0; j < likes.size(); j++) {
                                                if (likes.get(j).getLikeUserID() != application.getCurID())
                                                    likesnew.add(likes.get(j));
                                            }
                                            YNSingleton.getInstance().getStatusList().get(i).getLike().clear();
                                            YNSingleton.getInstance().getStatusList().get(i).setLike(likesnew);
                                        } else {
                                            YNLike ynLike = new YNLike();
                                            ynLike.setUpic(MineFragement.avatarPic);
                                            ynLike.setLikeStatus(Integer.parseInt(type));
                                            ynLike.setLikeUserID(application.getCurID());
                                            YNSingleton.getInstance().getStatusList().get(i).getLike().add(ynLike);
                                        }
                                        mTimeLineStatusAdapter.SyncLike();
                                    }
                                }
                                Toast.makeText(getActivity(), "点赞成功", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        Toast.makeText( getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        liteHttp.executeAsync(req);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MainScreen");
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MainScreen");
    }
}
